package com.sndscl.rpc.zk;

import com.alibaba.fastjson.JSONArray;
import com.sndscl.rpc.call.SndSclCall;
import com.sndscl.rpc.common.util.ZookeeperClient;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import java.util.*;

/**
 * @Description
 * @Author lsh
 * @Date 2020/10/14 13:26
 **/
public class NodeChangeWatcher implements Watcher {

    public ZookeeperClient zookeeperClient;

    public NodeChangeWatcher(ZookeeperClient zookeeperClient){
        this.zookeeperClient = zookeeperClient;
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        try {
            List<String> list = zookeeperClient.weatherDir(watchedEvent.getPath(),this);
            System.out.println(list);
            Map<String, HashSet<String>> serverListtMap = new HashMap<>();
            for(int i = 0; i < list.size(); i++){
                String node = list.get(i);
                byte[] data = zookeeperClient.getData(watchedEvent.getPath()+"/"+node);
                System.out.println(node + " "+ new String(data));

                JSONArray jsonArray = (JSONArray) JSONArray.parse(data);
                List interfaceList =  Arrays.asList(jsonArray.toArray());
                HashSet<String> interfaceSet = new HashSet<>();
                interfaceSet.addAll(interfaceList);
                serverListtMap.put(node,interfaceSet);
            }
            SndSclCall.getServerInterface(serverListtMap);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
